/**
 * Copyright &copy; 2012-2014 ThinkGem All rights reserved.
 */
package com.sx.admin.shiro;

import com.sx.admin.security.CoreWebUtils;
import com.sx.core.mybatis.SessionTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 表单验证（包含验证码）过滤类
 */
public class SecurityFormAuthenticationFilter extends FormAuthenticationFilter {

	public static final String DEFAULT_CAPTCHA_PARAM = "validateCode";
	public static final String DEFAULT_MESSAGE_PARAM = "message";
	public static final String DEFAULT_IDTYPE_PARAM = "idtype";

	private String captchaParam = DEFAULT_CAPTCHA_PARAM;
	private String messageParam = DEFAULT_MESSAGE_PARAM;
	Log log= LogFactory.getLog(getClass());
	@Autowired
	SessionTemplate sessionTemplate;
	@Autowired
	JdbcTemplate jdbcTemplate;


	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		if (password==null){
			password = "";
		}
		boolean rememberMe = isRememberMe(request);
		String host = CoreWebUtils.getIpAddress((HttpServletRequest) request);
		String captcha = getCaptcha(request);
		return new SecurityUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha);
	}

	public String getCaptchaParam() {
		return captchaParam;
	}

	protected String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}


	public String getMessageParam() {
		return messageParam;
	}
	
	/**
	 * 登录成功之后跳转URL
	 */
	public String getSuccessUrl() {
		return super.getSuccessUrl();
	}
	
	@Override
	protected void issueSuccessRedirect(ServletRequest request,
			ServletResponse response) throws Exception {
		CoreWebUtils.setSessionAttribute((HttpServletRequest) request,"userinfo",SecurityUserUtils.getOperator());
		SecurityUserUtils.isValidateCodeLogin(SecurityUserUtils.getOperator().getOpercode(), false, true);
		jdbcTemplate.update("UPDATE T_OPERATOR SET CHGDATE=? WHERE OPERCODE=?",new Date(),SecurityUserUtils.getOperator().getOpercode());
		 WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
	}

	/**
	 * 登录失败调用事件
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
                                     AuthenticationException e, ServletRequest request, ServletResponse response) {

		SecurityUsernamePasswordToken securityUsernamePasswordToken=(SecurityUsernamePasswordToken)token;
		String className = e.getClass().getName(), message = "";
		if (IncorrectCredentialsException.class.getName().equals(className)
				|| UnknownAccountException.class.getName().equals(className)){
			message = "用户或密码错误, 请重试.";
		}
		else if(className.equals(DisabledAccountException.class.getName())){
			message = e.getMessage();
			log.error("login>>>",e);
		}else{
			message = "系统出现点问题，请稍后再试！";
			log.error("login>>>",e);
		}
		if(SecurityUserUtils.isValidateCodeLogin(securityUsernamePasswordToken.getUsername(), true, false)){
			request.setAttribute("isValidateCodeLogin", true);
		}
        request.setAttribute(getFailureKeyAttribute(), className);
        request.setAttribute(getMessageParam(), message);
        return true;
	}
	
}